package com.fy.fyzf.api;

import android.util.Log;
import android.widget.Toast;


import com.fy.fyzf.base.BaseApp;
import com.fy.fyzf.base.BaseView;
import com.fy.fyzf.bean.BaseData;
import com.fy.fyzf.utils.AppUtils;
import com.google.gson.Gson;
import com.socks.library.KLog;

import cc.shinichi.library.tool.ui.ToastUtil;
import rx.Subscriber;

/**
 * @author ChayChan
 * @description: 抽取CallBack
 */
public abstract class SubscriberCallBack<T> extends Subscriber<BaseData<T>> {

    private BaseView baseView;
    private boolean isShowProgress = true;
    public SubscriberCallBack(){}
    public SubscriberCallBack(BaseView view) {
        baseView = view;
    }

    public SubscriberCallBack(BaseView view, boolean showProgress) {
        this.baseView = view;
        this.isShowProgress = showProgress;
        if (isShowProgress) {
            baseView.showLoading();
        }
    }
    @Override
    public void onNext(BaseData data) {
        if (isShowProgress) {
            baseView.dismissLoading();
        }
        if (data.code.equals("0")) {
            onSuccess((T) data);
        } else if (/*data.errCode.equals("E201001") ||*/ data.errMessage.equals("已在别的地方登录") || data.errMessage.equals("token不存在")) {
            baseView.dismissLoading();
            AppUtils.showToast("请重新登录！");
            AppUtils.toLogin(BaseApp.getContext());
        } else {
            baseView.dismissLoading();
            AppUtils.showToast(data.errMessage);
        }
    }

    @Override
    public void onCompleted() {

    }

    @Override
    public void onError(Throwable e) {
        baseView.dismissLoading();
        Log.e("onError", e.getLocalizedMessage().toString());
        KLog.e(e.getLocalizedMessage());
        onError();
    }

    protected abstract void onSuccess(T response);
    protected abstract void onError();

    protected void onFailure(BaseData response) {
    }
}
